/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.evosoft.vista.panel.empresa;

import com.evosoft.enumeration.TipoEmpresaEnum;
import com.evosoft.excepciones.CantCreateUpdate;
import com.evosoft.facade.FacadeFactory;
import com.evosoft.linker.App;
import com.evosoft.model.Empresa;
import com.evosoft.model.Persona;
import com.evosoft.model.Rol;
import com.evosoft.model.Tipo;
import com.evosoft.util.Sesion;
import com.evosoft.vista.dialog.CrearUsuario;
import com.evosoft.vista.panel.usuarios.ListaUsuarios;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JFrame;

/**
 *
 * @author Silex RPR
 */
public class CrearEmpresa extends javax.swing.JPanel {

    /**
     * Creates new form CrearDistribuidor
     */
    public String empresaNIT;
    
    
    //Se recibe en el constructor el nit de la empresa para la edición.
    public CrearEmpresa(String empresaNIT) {
        
        initComponents();
        
        if(empresaNIT == null) {
            jComboBox1.setVisible(false);
            jLabel6.setVisible(false);
        }else {
            jComboBox1.setVisible(true);
            jLabel6.setVisible(true);
            this.empresaNIT = empresaNIT;
            fillTextBoxes();
            fillComboBox();
        }

    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        jTextField1 = new javax.swing.JTextField();
        jLabel2 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        jLabel4 = new javax.swing.JLabel();
        jLabel5 = new javax.swing.JLabel();
        jTextField2 = new javax.swing.JTextField();
        jTextField3 = new javax.swing.JTextField();
        jTextField4 = new javax.swing.JTextField();
        jTextField5 = new javax.swing.JTextField();
        jLabel6 = new javax.swing.JLabel();
        jComboBox1 = new javax.swing.JComboBox();
        guardarButton = new javax.swing.JButton();
        cancelarButton = new javax.swing.JButton();
        jLabel7 = new javax.swing.JLabel();

        jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder("Descripcion"));

        jLabel1.setText("Nombre");

        jLabel2.setText("Direccion");

        jLabel3.setText("Correo");

        jLabel4.setText("NIT");

        jLabel5.setText("Telefono");

        jLabel6.setText("Super Administrador");

        jComboBox1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jComboBox1ActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addComponent(jLabel1)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(jTextField1))
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addGroup(javax.swing.GroupLayout.Alignment.LEADING, jPanel1Layout.createSequentialGroup()
                                .addComponent(jLabel6)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(jComboBox1, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                            .addGroup(jPanel1Layout.createSequentialGroup()
                                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(jLabel2)
                                    .addComponent(jLabel4))
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(jTextField2, javax.swing.GroupLayout.DEFAULT_SIZE, 237, Short.MAX_VALUE)
                                    .addComponent(jTextField5))))
                        .addGap(18, 18, 18)
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addGroup(jPanel1Layout.createSequentialGroup()
                                .addComponent(jLabel5)
                                .addGap(18, 18, 18)
                                .addComponent(jTextField4, javax.swing.GroupLayout.PREFERRED_SIZE, 234, javax.swing.GroupLayout.PREFERRED_SIZE))
                            .addGroup(jPanel1Layout.createSequentialGroup()
                                .addComponent(jLabel3)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                .addComponent(jTextField3, javax.swing.GroupLayout.PREFERRED_SIZE, 235, javax.swing.GroupLayout.PREFERRED_SIZE)))))
                .addContainerGap())
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(26, 26, 26)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel2)
                    .addComponent(jLabel3)
                    .addComponent(jTextField2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jTextField3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(21, 21, 21)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel4)
                    .addComponent(jLabel5)
                    .addComponent(jTextField4, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jTextField5, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 43, Short.MAX_VALUE)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel6)
                    .addComponent(jComboBox1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap())
        );

        guardarButton.setText("Guardar");
        guardarButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                guardarButtonActionPerformed(evt);
            }
        });

        cancelarButton.setText("Cancelar");
        cancelarButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cancelarButtonActionPerformed(evt);
            }
        });

        jLabel7.setText("CREANDO UNA NUEVA EMPRESA DISTRIBUIDORA");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addContainerGap()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addGroup(layout.createSequentialGroup()
                                .addGap(0, 0, Short.MAX_VALUE)
                                .addComponent(guardarButton, javax.swing.GroupLayout.PREFERRED_SIZE, 102, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(cancelarButton, javax.swing.GroupLayout.PREFERRED_SIZE, 97, javax.swing.GroupLayout.PREFERRED_SIZE))))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(175, 175, 175)
                        .addComponent(jLabel7)
                        .addGap(0, 0, Short.MAX_VALUE)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(24, 24, 24)
                .addComponent(jLabel7)
                .addGap(18, 18, 18)
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 31, Short.MAX_VALUE)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(guardarButton)
                    .addComponent(cancelarButton, javax.swing.GroupLayout.PREFERRED_SIZE, 25, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(10, 10, 10))
        );
    }// </editor-fold>//GEN-END:initComponents

    private void cancelarButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cancelarButtonActionPerformed
        setVisible(false);
        removeAll();
        App.getInstance().getMainWindow().getAppTabPanel().setComponentAt(0, new ListaEmpresa());
    }//GEN-LAST:event_cancelarButtonActionPerformed

    private void guardarButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_guardarButtonActionPerformed
        Empresa empresa = null;
        if(empresaNIT == null) { 
            empresa = new Empresa();    
        }
        else {
            try {
                empresa = FacadeFactory.getInstance().getEmpresaFacade().obtenerEmpresaPorNit(empresaNIT);
            } catch (Exception ex) {
                Logger.getLogger(CrearEmpresa.class.getName()).log(Level.SEVERE, null, ex);
            }
        }

        empresa.setNombre(jTextField1.getText());
        empresa.setCorreo(jTextField3.getText());
        empresa.setDireccion(jTextField2.getText());
        empresa.setNit(jTextField5.getText());
        empresa.setTelefono(jTextField4.getText());
        
        try {
            Persona personaEnSesion = Sesion.getInstance().getPersonaEnSesion();
            if(empresaNIT == null) { 
                //Validar para hacer esta ventana genérica
                empresa.setTipo(new Tipo(TipoEmpresaEnum.DISTRIBUIDOR));
                empresa.setSuperior(personaEnSesion.getEmpresa().getId());
                FacadeFactory.getInstance().getEmpresaFacade().crearEmpresa(empresa, personaEnSesion.getId());
            }
            else {
                int adminAnteriorId = empresa.getAdmin_id();
                if(adminAnteriorId != 0) {
                    Persona adminAnterior = FacadeFactory.getInstance().getPersonaFacade().obtenerPorId(adminAnteriorId);
                    //Al superadministrador anterior se deja como administrador básico
                    adminAnterior.setRol(new Rol(2));
                    FacadeFactory.getInstance().getPersonaFacade().actualizarPersona(adminAnterior, personaEnSesion.getId());
                }
                empresa.setAdmin_id(0);
                FacadeFactory.getInstance().getEmpresaFacade().actualizarEmpresa(empresa, personaEnSesion.getId());
                Persona nuevoAdmin = FacadeFactory.getInstance().getPersonaFacade().obtenerPorUsuario((String)jComboBox1.getSelectedItem());
                nuevoAdmin.setRol(new Rol(1));
                FacadeFactory.getInstance().getPersonaFacade().actualizarPersona(nuevoAdmin, personaEnSesion.getId());
                int adminId = nuevoAdmin.getId();
                empresa.setAdmin_id(adminId);
                FacadeFactory.getInstance().getEmpresaFacade().actualizarEmpresa(empresa, personaEnSesion.getId());
            }
            //Se actualiza la lista de usuarios
            App.getInstance().getMainWindow().getAppTabPanel().remove(1);
            App.getInstance().getMainWindow().getAppTabPanel().addTab("Usuarios", new ListaUsuarios());
        }
        catch(CantCreateUpdate e) {
            System.out.println(e.getMessage());
        } catch (Exception ex) {
            Logger.getLogger(CrearEmpresa.class.getName()).log(Level.SEVERE, null, ex);
        }
        setVisible(false);
        removeAll();
        App.getInstance().getMainWindow().getAppTabPanel().setComponentAt(0, new ListaEmpresa());
    }//GEN-LAST:event_guardarButtonActionPerformed

    private void jComboBox1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jComboBox1ActionPerformed
        
    }//GEN-LAST:event_jComboBox1ActionPerformed

    private void fillComboBox() {
        try {
            List<Persona> personas = null;
            Empresa empresa = FacadeFactory.getInstance().getEmpresaFacade().obtenerEmpresaPorNit(empresaNIT);
            int empresaId = empresa.getId();
            personas = FacadeFactory.getInstance().getPersonaFacade().obtenerPersonasPorEmpresa(empresaId);
            for (Persona p : personas) {
                 jComboBox1.addItem(p.getUsuario());
            }
            int adminId = empresa.getAdmin_id();
            if(adminId != 0) {
                String userAdmin = FacadeFactory.getInstance().getPersonaFacade().obtenerPorId(adminId).getUsuario();
                jComboBox1.setSelectedItem((String) userAdmin);
            }
        } catch (Exception ex) {
            Logger.getLogger(CrearEmpresa.class.getName()).log(Level.SEVERE, null, ex);
        }

    }
    
    
    private void fillTextBoxes() {
        Empresa empresa = null;
        try {
            empresa = FacadeFactory.getInstance().getEmpresaFacade().obtenerEmpresaPorNit(empresaNIT);
            jTextField1.setText(empresa.getNombre());
            jTextField2.setText(empresa.getDireccion());
            jTextField3.setText(empresa.getCorreo());
            jTextField5.setText(empresa.getNit());
            jTextField4.setText(empresa.getTelefono());
        }
        catch(Exception e) {
            Logger.getLogger(CrearEmpresa.class.getName()).log(Level.SEVERE, null, e);
        }
    }
    
    
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton cancelarButton;
    private javax.swing.JButton guardarButton;
    private javax.swing.JComboBox jComboBox1;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JLabel jLabel7;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JTextField jTextField1;
    private javax.swing.JTextField jTextField2;
    private javax.swing.JTextField jTextField3;
    private javax.swing.JTextField jTextField4;
    private javax.swing.JTextField jTextField5;
    // End of variables declaration//GEN-END:variables

    
}
